package com.ailot.cloud.base.log.aspect;

import com.ailot.cloud.base.log.annotation.Oplog;
import com.ailot.cloud.base.log.entity.SysLog;
import com.ailot.cloud.base.log.event.SysLogEvent;
import com.ailot.cloud.base.log.utils.SysLogUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.ApplicationEventPublisher;


/**
 * 日志切面
 *
 * @author litao
 */

@Aspect
@AllArgsConstructor
public class SysLogAspect {
    private final ApplicationEventPublisher publisher;

    @SneakyThrows
    @Around("@annotation(oplog)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint, Oplog oplog) {
        SysLog sysLog = SysLogUtil.AssembleSysLog();
        sysLog.setTitle(oplog.value());
        Long startTime = System.currentTimeMillis();
        Object obj = proceedingJoinPoint.proceed();
        Long endTime = System.currentTimeMillis();
        //计算执行时间
        sysLog.setTime(endTime - startTime);
        //异步发送日志
        publisher.publishEvent(new SysLogEvent(sysLog));
        return obj;
    }
}
